package org.aeon.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.jar.JarFile;

/**
 * @author: MissingAeon
 * @date: 2024/3/1 16:57
 * @description:
 */
@Slf4j
public class ImageSetUtil {

    private static final Map<String, Image> imageMap = new HashMap<>();

    static {
        try {
            final URL url = ImageSetUtil.class.getResource("/img");
            final URLConnection urlConnection;
            if (url != null) {
                urlConnection = url.openConnection();
                if (urlConnection instanceof JarURLConnection jarConnection) {
                    JarFile jarFile = jarConnection.getJarFile();
                    String prefix = "img/"; // 指定文件夹路径
                    // 获取指定文件夹下的条目流
                    jarFile.stream()
                            .filter(entry -> entry.getName().startsWith(prefix))
                            .forEach(entry -> {
                                try {
                                    final BufferedImage image = ImageIO.read(jarFile.getInputStream(entry));
                                    imageMap.put(entry.getName().substring(prefix.length()).split("\\.", 2)[0], image);
                                } catch (IOException e) {
                                    log.error("{},{}读取失败", e.getMessage(), entry.getName(), e);
                                }
                            });
                } else if ("file".equals(url.getProtocol())) {
                    File imgDir = new File(url.getFile());
                    if (imgDir.isDirectory()) {
                        File[] files = imgDir.listFiles();
                        if (files != null) {
                            for (File file : files) {
                                try {
                                    final BufferedImage image = ImageIO.read(file);
                                    imageMap.put(file.getName().split("\\.", 2)[0], image);
                                } catch (IOException e) {
                                    log.error("{},{}读取失败", e.getMessage(), file.getName(), e);
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    public static Image getImage(String imageName, int width, int height) {
        final Image image = Objects.requireNonNull(imageMap.get(imageName));
        return image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
    }
}
